﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using smsclictr.automation;
using System.Management;
using Microsoft.SystemCenter.Orchestrator.Integration;
using System.Xml;

namespace OpalisAddOn.SoftwareDist
{
    /// <summary>
    /// Adv is running
    /// </summary>
    [Activity("Advertisement is Running", Description = "Check if an Advertisement is running", ShowFilters=false, ShowInputs=true)]
    public class ADVRunning : IActivity
    {
        private String targetComputer;
        private String userName;
        private string password;

        public void Design(IActivityDesigner designer)
        {
            designer.AddInput("TargetComputer").WithComputerBrowser();
            designer.AddInput("UserName").NotRequired();
            designer.AddInput("Password").NotRequired().PasswordProtect();

            designer.AddOutput("AdvIsRunning").AsString();
        }

        public void Execute(IActivityRequest request, IActivityResponse response)
        {
            try
            {
                SMSClient oClient;
                targetComputer = request.Inputs["TargetComputer"].AsString();
                userName = request.Inputs["UserName"].AsString();
                password = request.Inputs["Password"].AsString();


                if (string.IsNullOrEmpty(userName))
                {
                    oClient = new SMSClient(targetComputer);
                }
                else
                {
                    oClient = new SMSClient(targetComputer, userName, password);
                }

                if (oClient.SoftwareDistribution.AdvIsRunning)
                {
                    response.Publish("AdvIsRunning", "true");
                }
                else
                {
                    response.Publish("AdvIsRunning", "false");
                }
            }
            catch(Exception ex)
            {
                response.ReportErrorEvent("Error", ex.Message);
                response.LogErrorMessage(ex.Message);
                throw new ActivityWarning();
            }
        }
    }

    /// <summary>
    /// SW Requires reboot
    /// </summary>
    [Activity("Software Requires Reboot", Description = "Check if an Advertisement is waiting for reboot", ShowFilters=false, ShowInputs=true)]
    public class SWRebootRequired : IActivity
    {
        private String targetComputer;
        private String userName;
        private string password;

        public void Design(IActivityDesigner designer)
        {
            designer.AddInput("TargetComputer").WithComputerBrowser();
            designer.AddInput("UserName").NotRequired();
            designer.AddInput("Password").NotRequired().PasswordProtect();

            designer.AddOutput("AdvRequiresReboot").AsString();
        }

        public void Execute(IActivityRequest request, IActivityResponse response)
        {
            SMSClient oClient;
            targetComputer = request.Inputs["TargetComputer"].AsString();
            userName = request.Inputs["UserName"].AsString();
            password = request.Inputs["Password"].AsString();

            if (string.IsNullOrEmpty(userName))
            {
                oClient = new SMSClient(targetComputer);
            }
            else
            {
                oClient = new SMSClient(targetComputer, userName, password);
            }

            bool bProcessed = false;
            foreach (ManagementObject MO in oClient.SoftwareDistribution.ReportStatusAtReboot)
            {
                response.Publish("AdvRequiresReboot", "true");
                bProcessed = true;
                break;
            }

            if(!bProcessed)
                response.Publish("AdvRequiresReboot", "false");

        }
    }

    /// <summary>
    /// Download SW
    /// </summary>
    [Activity("Software Download is running", Description = "Check if an Advertisement is downloading", ShowFilters = false, ShowInputs = true)]
    public class SWDownloadRunning : IActivity
    {
        public void Design(IActivityDesigner designer)
        {
            designer.AddInput("TargetComputer").WithComputerBrowser();
            designer.AddInput("UserName").NotRequired();
            designer.AddInput("Password").NotRequired().PasswordProtect();

            designer.AddOutput("AdvDownloadRunning").AsString().WithDescription("At least one download is in progress..") ;
        }

        public void Execute(IActivityRequest request, IActivityResponse response)
        {
            SMSClient oClient;
            string targetComputer = request.Inputs["TargetComputer"].AsString();
            string userName = request.Inputs["UserName"].AsString();
            string password = request.Inputs["Password"].AsString();

            if (string.IsNullOrEmpty(userName))
            {
                oClient = new SMSClient(targetComputer);
            }
            else
            {
                oClient = new SMSClient(targetComputer, userName, password);
            }


            bool bProcessed = false;
            foreach (ManagementObject MO in oClient.SoftwareDistribution.RunningDownloads)
            {
                response.Publish("AdvDownloadRunning", "true");
                bProcessed = true;
                break;
            }

            if (!bProcessed)
                response.Publish("AdvDownloadRunning", "false");

        }
    }

    /// <summary>
    /// Run Advertisement
    /// </summary>
    [Activity("Run Advertisement", Description="Re-Run an assigned advertisement", ShowFilters = false)]
    public class ReRunAdv : IActivity
    {
        public void Design(IActivityDesigner designer)
        {
            designer.AddInput("TargetComputer").WithComputerBrowser();
            designer.AddInput("UserName").NotRequired();
            designer.AddInput("Password").NotRequired().PasswordProtect();
            designer.AddInput("AdvertisementID");
            designer.AddInput("PackageID");
            designer.AddInput("ProgramID");
            designer.AddInput("Override ServiceWindow").NotRequired().WithBooleanBrowser().WithDefaultValue(true);

            designer.AddOutput("ScheduleID").AsString();
        }

        public void Execute(IActivityRequest request, IActivityResponse response)
        {
            SMSClient oClient;
            string targetComputer = request.Inputs["TargetComputer"].AsString();
            string userName = request.Inputs["UserName"].AsString();
            string password = request.Inputs["Password"].AsString();

            if (string.IsNullOrEmpty(userName))
            {
                oClient = new SMSClient(targetComputer);
            }
            else
            {
                oClient = new SMSClient(targetComputer, userName, password);
            }

            string sAdvID = request.Inputs["AdvertisementID"].AsString();
            string sPkgID = request.Inputs["PackageID"].AsString();
            string sProgID = request.Inputs["ProgramID"].AsString();


            if (request.Inputs.Contains("Override ServiceWindow"))
            {
                if (Boolean.Parse(request.Inputs["Override ServiceWindow"].AsString()))
                {
                    ManagementObject MO = oClient.SoftwareDistribution.GetAdvert(sAdvID, sPkgID, sProgID);
                    XmlDocument xDoc = new XmlDocument();
                    xDoc.LoadXml(MO["PRG_Requirements"].ToString());
                    XmlNode xNode = xDoc.SelectSingleNode(@"SWDReserved/OverrideServiceWindows");
                    xNode.InnerText = "TRUE";
                    MO.SetPropertyValue("PRG_Requirements", xDoc.InnerXml);
                    MO.Put();

                    oClient.Schedules.MachinePolicyEvaluator();

                    System.Threading.Thread.Sleep(1000);
                }
            }


            string sID = oClient.SoftwareDistribution.RerunAdv(sAdvID, sPkgID, sProgID, null);

            response.Publish("ScheduleID", sID);
        }
    }

}
